package furns.web;



import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public abstract class BasicServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //获取到action的值
        //如果使用了模板模式+反射+动态绑定，要满足action的value 和 方法名一致!!!
        String action = req.getParameter("action");

        try {
            //使用反射,获取当前对象的方法
            //1.this 就是请求的Servlet
            //2.declaredMethod 方法对象就是当前请求的servlet对应的"action名字" 的方法, 该方法对象(declaredMethod)
            //  是变化的,根据用户请求
            //3.使用模板模式+反射+动态机制===> 简化多个 if--else if---..
            Method method =
                    this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            //使用方法对象，进行反射调用
            method.invoke(this,req,resp);
        } catch (Exception e) {
            //java基础->异常机制
            //将发生的异常,继续throw
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
